<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../js/vue.js"></script>
  <script src="../js/vuex.js"></script>
  <script src="../js/vue-router.js"></script>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- 引入组件库 -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script src="../js/axios.js"></script>
  <script src="../js/qs.js"></script>
</head>

<body>
  <div id="app">
    <router-view></router-view>
  </div>

  <script>
    let qs = Qs;

    let login = {
      data() {
        return {
          loginData: {}
        }
      },
      template: `
        <div>
          <h1>欢迎登陆</h1>  
          用户名：<input type="text" v-model="loginData.username">
          密码：<input type="text" v-model="loginData.password">
          <button @click="loginHandler">登录</button>
        </div>
      `,
      methods: {
        loginHandler() {
          axios.defaults.headers.post['Content-Type'] = 'application/json';
          axios({
            url: 'http://47.94.46.113:8888/user/login',
            method: 'post',
            data: JSON.stringify(this.loginData)
          }).then(res => {
            sessionStorage.setItem('token', res.data.data.token)
            // 登录成功，跳转至首页
            this.$router.push({ path: '/index' })
          })
        }
      }
    }

    let index = {
      data() {
        return {}
      },
      template: `
        <div>
          <h1>欢迎使用</h1>  
        </div>
      `
    }

    // 定义路由
    let router = new VueRouter({
      routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: login },
        { path: '/index', component: index },
      ]
    })
    // 设置路由全局前置守卫
    router.beforeEach((to, from, next) => {
      let token = sessionStorage.getItem('token');
      if (to.path != '/login' && !token) {
        alert('请先登录！');
        next('/login')
      }
      next();
    })

    let vm = new Vue({
      el: '#app',
      data: {

      },
      methods: {

      },
      // 注册路由
      router
    })
  </script>
</body>

</html>